<template>
  <div class="login-page">
    <div class="login-form">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
// import { setToken } from '@/utils/auth'; // get token from cookie
import { mapActions } from 'vuex';

export default {
  name: 'Login',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        userName: '',
        pass: '',
      },
      rules: {
        userName: [
          { required: true, message: '请输入真实名称', trigger: 'blur' },
          {
            min: 2,
            max: 12,
            message: '长度在2到12个字符',
            trigger: 'blur',
          },
        ],
        pass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    ...mapActions('user', ['postLogin', 'getInfo']),
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.postLogin(this.ruleForm)
            .then((data) => {
              if (data.data) {
                const resp = data.data;
                this.getInfo(resp.id);
                this.$message({
                  type: 'success',
                  message: data.message,
                });
                this.$router.push({ path: this.redirect || '/' });
              }
            })
            .catch((err) => {
              this.$message({
                type: 'info',
                message: err.message,
              });
            });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    $route: {
      handler(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.login-page {
  width: 100%;
  height: 100%;
  background-color: teal;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-form {
    width: 100%;
    max-width: 400px;
    border: 1px solid #fff;
    background-color: #ffffff;
    box-shadow: 0px 0px 10px #ffffff;
    padding: 40px 15px 15px;
  }
}
</style>
